unit UConflictSelector;

interface

uses SysUtils, Classes, IniFiles, DB, Generics.Collections, UField, UTable;

type
  TConflictSelector = class(TList<TSchLookupField>)
    function GetRows: string;
    function GetNames(D: TDataSet; const ShowHeaders: boolean = true): string;
    function GetWhere(D: TDataSet): string;
  end;

var
  SchedConflictTable: TTable;
  Nodes: array[1..5] of array[1..3] of TConflictSelector;
  ConflictsFile: TIniFile;


implementation

{ TConflictSelector }

function TConflictSelector.GetNames(D: TDataSet; const ShowHeaders: boolean): string;
var
  l: TStringList;
  f: TSchLookupField;
begin
  l := TStringList.Create;
  for f in Self do begin
    if ShowHeaders then
      l.Append(Format('%s: %s;', [f.Short, D.FieldValues[f.Alias]]))
    else
      l.Append(D.FieldValues[f.Alias]);
  end;
  if ShowHeaders then
    Result := Conjuct(l, ' ')
  else
    Result := Conjuct(l, CComma);
  FreeAndNil(l);
end;

function TConflictSelector.GetRows: string;
var
  l: TStringList;
  f: TSchLookupField;
begin
  l := TStringList.Create;
  for f in Self do begin
    l.Append(f.TableDef.Key);
    l.Append(f.Alias);
  end;
  Result := Conjuct(l, CComma);
  FreeAndNil(l);
end;

function TConflictSelector.GetWhere(D: TDataSet): string;
var
  l: TStringList;
  f: TSchLookupField;
begin
  l := TStringList.Create;
  for f in Self do
    l.Append(f.TableDef.Key + CEqualis + D.FieldByName(f.TableDef.Key).AsString);
  Result := Conjuct(l, CAnd);
  FreeAndNil(l);
end;

procedure InitializeUnit;
var
  i, j, k: integer;
  l: TStringList;
  s: string;
begin
  l := TStringList.Create;
  ConflictsFile := TIniFile.Create(WorkingDir + 'config\conflicts.ini');
  SchedConflictTable := CreateTable(SchedName, '', ConflictsFile, -1);
  for i := 1 to 5 do
    for j := 1 to 3 do begin
      l.Clear;
      s := Format('%d.%d', [i, j]);
      ConflictsFile.ReadSectionValues(s, l);
      Nodes[i, j] := TConflictSelector.Create;
      for k := 0 to l.Count - 1 do
        Nodes[i, j].Add(SchedConflictTable.FieldByRefKey(l.ValueFromIndex[k]));
    end;
  FreeAndNil(l);
end;

procedure FinalizeUnit;
var
  i, j: integer;
begin
  for i := Low(Nodes) to High(Nodes) do
    for j := Low(Nodes[i]) to High(Nodes[i]) do
      FreeAndNil(Nodes[i, j]);
  FreeAndNil(SchedConflictTable);
  FreeAndNil(ConflictsFile);
end;

initialization
  InitializeUnit;

finalization
  FinalizeUnit;

end.
